/**
 * All rights Reserved, Designed By 信鸥科技
 * project : Innovation-design
 * Created by youquer on 17/11/10.
 * 注意：本内容仅限于信鸥科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 * Description:
 *
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  TreeSelect, Form, Input, DatePicker, Select, Button, notification, Card, InputNumber, Radio, Icon, Tooltip, Upload, Modal
} from 'antd';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const { TextArea } = Input;
const Option = Select.Option;
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './NewsAdd.less';
import queryString from 'query-string';
import { urlAction } from '../../utils/global';
import  Editor  from '@/components/Ueditor/Ueditor';

const FormItem = Form.Item;
@connect(state => ({
  news: state.news,
}))
@Form.create()

export default class NewsAdd extends PureComponent {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "news/clear"
    });
    var search = queryString.parse(this.props.location.search);
    if (search.id) { //修改
      dispatch({
        type: 'news/toUpdate',
        payload: {id: search.id}
      });
    }

  }

  onInputChange(e){
    var key = e.target.name;
    var value = e.target.value;
    const { dispatch } = this.props;
    var t = {};
    t[key] = value;
    dispatch({
      type: 'news/save',
      payload: t
    })
  }

  onInputNumChange(key, value){
    var t = {};
    t[key] = value;
    this.props.dispatch({
      type: 'news/save',
      payload: t
    })
  }

  onSelectChange(key, e){
    const { dispatch } = this.props;
    var t = {};
    t[key] = e;
    dispatch({
      type: 'news/save',
      payload: t
    })
  }

  btnAct(){
    const {dispatch} = this.props;
    const {news} = this.props;
    const {title, cover, type, content, id, sort, appendix, appendixName} = news;
    var data;
    if (id){
      data = {title, cover, type, content, sort, id};
      dispatch({
        type: "news/update",
        payload: data
      })
    } else {
      data = {title, cover, type, content, sort};
      dispatch({
        type: "news/add",
        payload: data
      })
    }

  };

  //图片
  handleCancel() {
    const {dispatch} = this.props;
    dispatch({
      type: 'news/save',
      payload: {previewVisible: false}
    })
  }

  handlePreview(file) {
    const {dispatch} = this.props;
    dispatch({
      type: 'news/save',
      payload: {
        previewImage: file.url || file.thumbUrl,
        previewVisible: true,
      }
    });
  }

  handleChanges(fileList) {
    const {dispatch} = this.props;
    dispatch({
      type: "news/save",
      payload: {fileList: fileList.fileList}
    });
    var file = fileList.fileList[0];
    var fileRemoved = fileList.file;
    if (file){
      if (file.status === 'done') {
        var fileName = file.response.body.fileName;
        dispatch({
          type: "news/save",
          payload: {cover: fileName}
        });
      }
    } else if (fileRemoved.status === "removed"){
      dispatch({
        type: "news/save",
        payload: {cover: ""}
      });
    }
  }


  render() {
    const { submitting, news } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { id, title, cover, sort, type, content, appendix, previewVisible, previewImage, fileList, fileLists} = news;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className={styles.ant_upload_text}>Upload</div>
      </div>
    );

    var formItemArray = [];
    var keyArray = ["title", "cover", "type", "sort", "content"];
    var valueArray = [title, cover, type, sort, content];
    var labelArray = ["名称", "图片", "类型", "排序", "内容"];


    for (var i = 0; i<keyArray.length; i++){
      var itemKey = labelArray[i] + "不能为空";
      switch (i){
        case 1: //图片
          if (this.props.location.pathname == '/newsAdd'){
            formItemArray.push(
              <FormItem
                key={"news-item-" + i}
                {...formItemLayout}
                label={labelArray[i]}
              >
                {getFieldDecorator(keyArray[i], {
                  rules: [{
                    required: true, message: itemKey,
                  }],
                  initialValue: valueArray[i]
                })(
                  <div>
                    <Upload
                      action={urlAction}
                      listType="picture-card"
                      fileList={fileList}
                      accept="image/jpeg,image/jpg"
                      data={{projectName:'lawyer', thumbnail_size: 1000}}
                      onPreview={this.handlePreview.bind(this)}
                      onChange={this.handleChanges.bind(this)}
                    >
                      {fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel.bind(this)}>
                      <img className={styles.look_large_img} alt="example" src={previewImage}/>
                    </Modal>
                  </div>
                )}
              </FormItem>
            );
          }

          break;
        case 2:

          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >
              {getFieldDecorator(keyArray[i], {
                rules: [{
                  required: true, message: itemKey,
                }],
                initialValue: valueArray[i] + ""
              })(
                <Select className={styles.full_width} onChange={this.onSelectChange.bind(this, "type")} >
                  <Option value="0">请选择</Option>
                </Select>
              )}
            </FormItem>
          );

          break;
        case 3:
          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >
              {getFieldDecorator(keyArray[i], {
                rules: [{
                  required: true, message: itemKey,
                }],
                initialValue: valueArray[i]
              })(
                <InputNumber min={0} className={styles.full_witdh} name="sort" placeholder="请输入排序" onChange={this.onInputNumChange.bind(this, "sort")} />
              )}
            </FormItem>
          );
          break;
        case 4:
          formItemArray.push(
            <div key={"news-item-" + i} title="内容" className={styles.reactQuill}>
              <Editor type="news" dispatch={this.props.dispatch} updateEditorContent={content} id="content" height="200" />
            </div>
          );
          break;
        default:
          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >
              {getFieldDecorator(keyArray[i], {
                rules: [{
                  required: true, message: itemKey,
                }],
                initialValue: valueArray[i]
              })(
                <Input maxLength="50" name={keyArray[i]} onChange={this.onInputChange.bind(this)} placeholder={"请输入" + labelArray[i]} />
              )}
            </FormItem>
          );
          break;
      }
    }

    var typeName = "";

    var pathname = this.props.location.pathname;
    if (pathname == '/newsAdd'){
      typeName = '新闻';
    } else {
      typeName = '文件';
    }

    return (
      <PageHeaderLayout title={id? "修改" + typeName : "添加" + typeName} content="">
        <Card bordered={false}>
          <Form
            style={{ marginTop: 8 }}
          >
            {formItemArray}
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" onClick={this.btnAct.bind(this)} loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
